<script setup lang="ts">
import { ElMessageBox } from 'element-plus';
import { getCodeImg, register, sendEmailCode, verifyEmailCode, sendPhoneCode, verifyPhoneCode } from '@/api/login';
import { getConfigKey } from '@/api/system/config';
import { getLoginStyle } from '@/utils/widthUtils';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const registerFormRef = ref<ElFormInstance>();

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  code: '',
  uuid: ''
});

const equalToPassword = (rule, value, callback) => {
  if (registerForm.value.password !== value) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const registerRules = {
  username: [
    { required: true, trigger: 'blur', message: '请输入您的账号' },
    { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入您的密码' },
    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: '请再次输入您的密码' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const codeUrl = ref('');
const loading = ref(false);
const captchaEnabled = ref(true);
const emileEnabled = ref(false);
const phoneEnabled = ref(false);

const useEmile = () => {
  captchaEnabled.value = false;
  phoneEnabled.value = false;
  emileEnabled.value = true;
};

const useUsername = () => {
  getConfigKey('sys.account.captchaEnabled').then(res => captchaEnabled.value = res.msg === 'true');
  phoneEnabled.value = false;
  emileEnabled.value = false;
};

const usePhone = () => {
  captchaEnabled.value = false;
  phoneEnabled.value = true;
  emileEnabled.value = false;
};

const handleRegister = () => {
  registerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      let handleRegister = register;
      if (emileEnabled.value) {
        registerForm.value.email = registerForm.value.username;
        handleRegister = verifyEmailCode;
      } else if (phoneEnabled.value) {
        registerForm.value.phone = registerForm.value.username;
        handleRegister = verifyPhoneCode;
      }
      handleRegister(registerForm.value).then(res => {
        const username = registerForm.value.username;
        ElMessageBox.alert('<font color=\'red\'>恭喜你，您的账号 ' + username + ' 注册成功！</font>', '系统提示', {
          dangerouslyUseHTMLString: true,
          type: 'success'
        }).then(() => {
          router.push('/login');
        }).catch(() => {
        });
      }).catch(() => {
        loading.value = false;
        if (captchaEnabled) {
          getCode();
        }
      });
    }
  });
};

const getCode = () => {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img;
      registerForm.value.uuid = res.uuid;
    }
  });
};

const sendCode = () => {
  if (emileEnabled.value) {
    registerForm.value.email = registerForm.value.username;
    sendEmailCode(registerForm.value);
  } else if (phoneEnabled.value) {
    registerForm.value.phoneNumber = registerForm.value.username;
    sendPhoneCode(registerForm.value);
  }
};

const loginStyle = ref({
  fromWidth: {
    width: '60%'
  },
  titleShow: true,
  formStyle: {
    left: '60%',
    top: '52%',
    width: 'auto'
  },
  containerSize: {
    width: '60%',
    height: '60%'
  },
  containerStyle: {
    borderRadius: '10px'
  }
});

onMounted(() => {
  loginStyle.value = getLoginStyle();
  getCode();
});

</script>

<template>
  <div class="register">
    <div class="container" :style="loginStyle.containerSize">
      <div class="container-style" :style="loginStyle.containerStyle">
        <div class="title-box" v-show="loginStyle.titleShow">
          <div class="title-container">
            <div class="title-style">
              <div class="logo">
                后台管理系统
              </div>
            </div>
          </div>
        </div>
        <div class="form-box" :style="loginStyle.fromWidth">
          <div class="form-container">
            <div class="logo" v-show="!loginStyle.titleShow">
              后台管理系统
            </div>
            <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" class="form-style"
                     :style="loginStyle.formStyle">
              <el-form-item prop="username" v-if="emileEnabled">
                <el-input v-model="registerForm.username" type="text" size="large" auto-complete="off"
                          placeholder="邮箱">
                  <template #prefix>
                    <svg-icon icon-class="email" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="username" v-else-if="phoneEnabled">
                <el-input v-model="registerForm.username" type="text" size="large" auto-complete="off"
                          placeholder="手机号">
                  <template #prefix>
                    <svg-icon icon-class="phone" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="username" v-else>
                <el-input v-model="registerForm.username" type="text" size="large" auto-complete="off"
                          placeholder="账号">
                  <template #prefix>
                    <svg-icon icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="registerForm.password" type="password" size="large" auto-complete="off"
                          placeholder="密码"
                          @keyup.enter="handleRegister">
                  <template #prefix>
                    <svg-icon icon-class="password" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="confirmPassword">
                <el-input v-model="registerForm.confirmPassword" type="password" size="large" auto-complete="off"
                          placeholder="确认密码" @keyup.enter="handleRegister">
                  <template #prefix>
                    <svg-icon icon-class="password" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code" v-if="captchaEnabled">
                <el-space>
                  <el-input size="large" v-model="registerForm.code" auto-complete="off" placeholder="验证码"
                            style="width: 50%"
                            @keyup.enter="handleRegister">
                    <template #prefix>
                      <svg-icon icon-class="validCode" />
                    </template>
                  </el-input>
                  <div style="display: flex">
                    <img :src="codeUrl" @click="getCode" class="code-img" />
                  </div>
                </el-space>
              </el-form-item>
              <el-form-item prop="code" v-if="emileEnabled || phoneEnabled">
                <el-space>
                  <el-input size="large" v-model="registerForm.code" auto-complete="off" placeholder="验证码"
                            style="width: 50%"
                            @keyup.enter="handleRegister">
                    <template #prefix>
                      <svg-icon icon-class="validCode" />
                    </template>
                  </el-input>
                  <div style="display: flex">
                    <el-button class="code-img"
                               @click="sendCode">发送验证码
                    </el-button>
                  </div>
                </el-space>
              </el-form-item>
              <el-form-item style="width:100%;">
                <el-button :loading="loading" size="large" type="primary" style="width:100%;"
                           @click.prevent="handleRegister">
                  <span v-if="!loading">注 册</span>
                  <span v-else>注 册 中...</span>
                </el-button>
                <div style="display: flex; justify-content: space-between;width: 100%;">
                  <el-link class="link-type" :underline="false" @click="$router.push('/login')">已有账户登录
                  </el-link>
                  <el-link class="link-type" :underline="false" @click="useEmile()" v-if="!emileEnabled">邮箱注册
                  </el-link>
                  <el-link class="link-type" :underline="false" @click="usePhone()" v-if="!phoneEnabled">手机号注册
                  </el-link>
                  <el-link class="link-type" :underline="false" @click="useUsername()"
                           v-if="emileEnabled || phoneEnabled">账号注册
                  </el-link>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <!--  底部  -->
    <div class="el-register-footer">
      <span></span>
    </div>
  </div>
  <div class="register">

    <!--  底部  -->
    <div class="el-register-footer">
      <span></span>
    </div>
  </div>
</template>

<style lang='scss' scoped>
.register {
  height: 100%;
  width: 100%;
  background-image: url('@/assets/images/login-background.jpg');
  background-size: cover;
}

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.container-style {
  width: 100%;
  height: 100%;
  border: none;
  background-color: #fff;
  display: flex;
  //background-color: rgba(255, 255, 255, 0.2); /* 半透明背景 */
  //backdrop-filter: blur(10px); /* 创建毛玻璃效果 */
}

.logo {
  padding-top: 1em;
  font-family: 宋体;
  font-size: 2em;
  font-weight: bolder;
  text-align: center;
  color: #531dab;
}

.form-box {
  height: 100%;
  border-radius: 25px
}

.form-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.form-style {
  position: absolute;
  transform: translate(-50%, -50%);
}

.title-box {
  height: 100%;
  flex-grow: 1;
  border-radius: 25px;
  position: relative
}

.title-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.title-style {
  width: 600px;
  height: 500px;
  border-radius: 25px;
  background: #9cc8f7;
  box-shadow: 3px 3px 12px #85aad2,
  -3px -3px 12px #b3e6ff;
}

.login-form-forgot {
  float: right;
}

.login-form-button {
  width: 100%;
}

.code-img {
  margin: auto;
  width: 100px;
  height: 39px;
  border-radius: 5px;
}
</style>
